<template>
	<view class="ide-content">
		<view v-if="approveStatus == 0 || approveStatus == 2">
			<u--form
					labelPosition="left"
					:model="formModel"
					:rules="rules"
					ref="uForm"
			>
				<u-form-item
						label="身份选择"
						labelWidth="100"
						prop="userInfo.identityName"
						borderBottom
						@click="open(1)"
						:required="true"
						ref="item1"
				>
					<u--input
							v-model="formModel.userInfo.identityName"
							disabledColor="#ffffff"
							placeholder="请选择认证身份"
							border="none"
							:disabled="isDisabled"
					></u--input>
					<u-icon
							slot="right"
							name="arrow-right"
					></u-icon>
				</u-form-item>
				 <u-form-item
						label="编号"
						prop="userInfo.sno"
						borderBottom
						:required="true"
						ref="item1"
				>
					<u--input
							v-model="formModel.userInfo.sno"
							placeholder="请输入学号或者教师编号"
							border="none"
							:disabled="isDisabled"
					></u--input>
				</u-form-item>
				<u-form-item
						label="学院"
						prop="userInfo.college"
						borderBottom
						:required="formModel.userInfo.identity==0"
						ref="item1"
				>
					<u--input
							v-model="formModel.userInfo.college"
							placeholder="请输入学院"
							border="none"
							:disabled="isDisabled"
					></u--input>
				</u-form-item>
				<u-form-item
						label="专业"
						prop="userInfo.specialty"
						:required="formModel.userInfo.identity==0"
						borderBottom
						ref="item1"
				>
					<u--input
							v-model="formModel.userInfo.specialty"
							placeholder="请输入学习的专业"
							border="none"
							:disabled="isDisabled"
					></u--input>
				</u-form-item>
				
				<u-form-item
						label="哪一届"
						labelWidth="60"
						:required="formModel.userInfo.identity==0"
						prop="userInfo.step"
						borderBottom
						ref="item1"
						@click="open(2)"
				>
					<u--input
							v-model="formModel.userInfo.step"
							disabledColor="#ffffff"
							placeholder="请选择哪一届"
							border="none"
							:disabled="isDisabled"
					></u--input>
					<u-icon
							slot="right"
							name="arrow-right"
					></u-icon>
				</u-form-item>
				
				<u-form-item
						label="身份信息上传(例如: 学生证,教师证)"
						labelWidth="400"
						ref="item1"
				>
				</u-form-item>
				<u-form-item
						label=" "
						labelWidth="50"
						ref="item1"
				>
				<view style="margin: 10rpx auto;">
					<u-upload
						:fileList="fileList"
						@afterRead="afterRead"
						@delete="deletePic"
						name="1"
						accept="image"
						multiple
						:maxCount="1"
						:previewFullImage="true"
						width="250"
						height="150"
					>
						<image :src="imgSrc" mode="widthFix" style="width: 250px;height: 150px;"></image>
					</u-upload>
				</view>
				
				</u-form-item> 
			</u--form>
			<!-- 提交按钮 -->
			<view style="position: fixed;text-align: center;bottom: 20rpx;width: 100%;" v-if="approveStatus == 0">
				<u-button color="#2979ff" @click="submit" customStyle="width: 400rpx;">提交认证</u-button>
			</view>
		</view>
		
		<view v-else-if="approveStatus == 1" style="width: 100%;text-align: center;">
			<view style="width:100px;margin: 200px auto;text-align: center;">
				<text style="color: rgb(162, 162, 162);font-weight: blod;font-size: 18px;">认证信息正在审核中...</text>
			</view>
		</view>
		<view v-else style="width: 100%;text-align: center;margin-top: 200px;">
			<view style="width:120px;margin: 20px auto;text-align: center;">
				<text style="color: red;font-weight: blod;font-size: 18px;">认证审核失败!</text>
			</view>
			<view style="width: 120px;height: 70px;margin: 20px auto;">
				<u-button type="primary" text="重新提交认证" @click="approveStatus=0"></u-button>
			</view>
		</view>
		<u-action-sheet
				:show="showIdentity"
				:actions="identityActions"
				title="请选择身份"
				@close="showIdentity = false"
				@select="identitySelect"
		>
		</u-action-sheet>
		<u-picker :show="showStep" ref="uPicker" :columns="actions" @change="stepSelect" @cancel="showStep=false" @confirm="showStep=false"></u-picker>
		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
	import {getUserApprove, getUploadToken, userInfoUpdate, loadToken} from '@/utils/api.js'
	export default {
		data() {
			return {
				showStep: false,
				showIdentity: false,
				isDisabled: false,
				fileList: [],
				lookImgPre: '',
				imgSrc: 'https://cdn.uviewui.com/uview/demo/upload/positive.png',
				formModel: {
					userInfo: {
						sno: '19140539318',
						college: '',
						specialty: '',
						step: '',
						identity: 0,
						approveImg: '',
						identityName: '学生',
					}
				},
				approveStatus: 0,
				actions: [[]],
				identityActions: [{id: 0, name: '学生',},{id: 1, name: '教师',}],
				rules: {
					'userInfo.identityName': {
						type: 'string',
						required: true,
						message: '请选择认证身份',
						trigger: ['blur', 'change']
					},
					'userInfo.sno': {
						type: 'string',
						required: true,
						message: '请填写编号',
						trigger: ['blur', 'change']
					},
					'userInfo.college': {
						type: 'string',
						required: true,
						message: '请填写学院',
						trigger: ['blur', 'change']
					},
					'userInfo.specialty': {
						type: 'string',
						required: true,
						message: '请填写所学专业',
						trigger: ['blur', 'change']
					},
					'userInfo.step': {
						type: 'string',
						required: true,
						message: '请选择哪一届',
						trigger: ['blur', 'change']
					},
				},
			}
		},
		methods: {
			open(sign){
				//认证成功, 不能再选择
				if(this.approveStatus == 2) return
				if(sign == 1){
					this.$refs.uForm.clearValidate()
					this.showIdentity = true
				}else {
					this.showStep = true
				}
			},
			loadUserInfo(){
				getUserApprove().then(res => {
					if(res == null || res.approveStatus == 0){
						return
					}
					this.approveStatus = res.approveStatus
					this.imgSrc = res.approveImg
					
					this.formModel.userInfo = res
					let index = res.identity
					if(index == -1){	//代表认证过, 审核未通过
						//是学生还教师身份
						if(res.step != null && res.step != ''){
							index = 0
						}else {
							index = 1
						}
					}
					this.formModel.userInfo.identity = index
					this.formModel.userInfo.identityName = this.identityActions[index].name
					if(this.approveStatus == 2){
						this.isDisabled = true
						//更新token
						loadToken().then(token => {
							if(token != null && token != ''){
								uni.setStorage({
									key: 'loginToken',
									data: `${token}`
								})
							}
						})
					}
				})
			},
			identitySelect(e) {
				this.formModel.userInfo.identity = e.id
				this.formModel.userInfo.identityName = e.name
				this.didiFamily = e.id
				this.$refs.uForm.validateField('userInfo.identityName')
			},
			stepSelect(e) {
				console.log("val" ,this.actions[0][e.index])
				// 微信小程序无法将picker实例传出来，只能通过ref操作
				// picker = this.$refs.uPicker
				this.formModel.userInfo.step = this.actions[0][e.index]
				this.$refs.uForm.validateField('userInfo.step')
			},
			getToken(){
				getUploadToken().then(res=>{
					this.token = res.uploadToken
					this.lookImgPre = res.lookImgPre
				})
			},
			// 删除图片
			deletePic(event) {
				this.fileList.splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				if(this.approveStatus == 2) return
				const _that = this
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = _that.fileList.length
				//let fileListLen = _that[`fileList${event.name}`].length
				lists.map((item) => {
					_that.fileList.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await _that.uploadFilePromise(lists[i].url)
					let item = _that.fileList[fileListLen]
					if(result.hash != null){
						_that.formModel.userInfo.approveImg = _that.lookImgPre + result.key
						_that.fileList.splice(fileListLen, 1, Object.assign(item, {
							status: 'success',
							message: '成功',
							url: _that.lookImgPre + result.key
						}))
						fileListLen++
					}else {
						getApp().globalData.toast[1].message = '图片上传失败!'
						_that.$refs.uToast.show({
							...getApp().globalData.toast[1],
							complete() {
								_that.fileList.splice(i, 1)
							}
						})
					}
					
				}
			},
			uploadFilePromise(url) {
				const that = this
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: 'http://upload.qiniup.com/', 
						filePath: url,
						name: 'file',
						timeout: 5000,
						formData: {
							token: that.token,
							//key: url.substr(url.indexOf("0/") + 2)
						},
						success: (res) => {
							resolve(JSON.parse(res.data))
						},
						fail: (error) => {
							console.log("错误!", error)
							resolve(error)
						}
					});
				})
			},
			submit(){
				const _that = this
				this.$refs.uForm.validate().then(res => {
					console.log('commit userinfo', _that.formModel.userInfo)
					userInfoUpdate(_that.formModel.userInfo).then(res => {
						getApp().globalData.toast[0].message = '提交认证信息成功'
						_that.$refs.uToast.show({
							...getApp().globalData.toast[0],
							complete() {
								//当前页
								let pages = getCurrentPages()
								//上个页面
								let beforePage = pages[pages.length - 2]
								let backUrl = beforePage.route
								uni.$u.route({
									type: 'redirect',
									url: backUrl
								})
							}
						})
					})
				}).catch(errors => {
					console.log('校验失败', errors)
				})
				
			},
			setR(newValue){
				this.rules = {
					'userInfo.identityName': {
						type: 'string',
						required: true,
						message: '请选择认证身份',
						trigger: ['blur', 'change']
					},
					'userInfo.sno': {
						type: 'string',
						required: true,
						message: '请填写编号',
						trigger: ['blur', 'change']
					},
					'userInfo.college': {
						type: 'string',
						required: newValue==0,
						message: '请填写学院',
						trigger: ['blur', 'change']
					},
					'userInfo.specialty': {
						type: 'string',
						required: newValue==0,
						message: '请填写所学专业',
						trigger: ['blur', 'change']
					},
					'userInfo.step': {
						type: 'string',
						required: newValue==0,
						message: '请选择哪一届',
						trigger: ['blur', 'change']
					},
										
				}
			}
		},
		onReady() {
			//this.setR(0)
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			this.$refs.uForm.setRules(this.rules)
			for (let i = 15; i < 40; i++) {
				this.actions[0].push(`${i}级`)
			}
			this.loadUserInfo()
			this.getToken()
		},
		computed: {
			didiFamily:{
				get:function(){
				  return this.formModel.userInfo.identity
				},
				//setter
				set:function(newValue){
					console.log('computed set', newValue)
					// 这里由于该计算属性被赋值，将被调用
					this.setR(newValue)
				},
			}
		},
		created() {
			
		},
	}
</script>

<style lang="scss" scoped>
	.ide-content{
		padding: 30rpx;
	}
</style>
